import os
import pandas as pd
import win32com.client as win32
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import fitz
from PIL import Image

def excel_to_pdf(excel_path, pdf_path):
    # 确保Excel路径存在
    if not os.path.exists(excel_path):
        raise FileNotFoundError(f"找不到文件: {excel_path}")
    
    # 使用pandas读取Excel文件（这里主要是为了验证文件是否可读）
    df = pd.read_excel(excel_path)
    print("成功读取Excel文件")

    # 初始化Excel应用程序
    excel = win32.Dispatch("Excel.Application")
    excel.Visible = False  # 设置为False以隐藏Excel应用程序

    try:
        # 打开工作簿
        wb = excel.Workbooks.Open(os.path.abspath(excel_path))
        
        # 另存为PDF
        wb.ExportAsFixedFormat(0, os.path.abspath(pdf_path))  # 0代表PDF格式
        print(f"成功将Excel文件转换为PDF: {pdf_path}")
        return pdf_path
    except Exception as e:
        print(f"转换过程中出现错误: {e}")
        return None
    finally:
        # 关闭工作簿和Excel应用程序
        wb.Close(SaveChanges=False)
        excel.Quit()



def excel_to_img(excel_path, img_path):
    # 确保Excel路径存在
    if not os.path.exists(excel_path):
        raise FileNotFoundError(f"找不到文件: {excel_path}")
    
    # 使用pandas读取Excel文件（这里主要是为了验证文件是否可读）
    df = pd.read_excel(excel_path)
    print("成功读取Excel文件")

    # 设置图形大小
    plt.figure(figsize=(10, 6))
    # 配置中文字体
    font = FontProperties(fname=r'./ttf/SIMSUN.TTC')  # 根据实际情况调整路径

    # 将DataFrame绘制成表格
    ax = plt.subplot(111)
    ax.axis('tight')
    ax.axis('off')

    # 绘制表格pip install -e .
    table = ax.table(cellText=df.values, colLabels=df.columns, cellLoc='center', loc='center')

    # 调整列宽
    for key, cell in table.get_celld().items():
        cell.set_height(0.04)
        if key[1] == -1:  # 表头
            cell.set_fontsize(12)
            cell.set_facecolor("#DDDDDD")
        else:
            cell.set_fontsize(10)
                # 设置字体属性
        text = cell.get_text()
        text.set_fontproperties(font)

    # 保存为图片
    plt.savefig(img_path, bbox_inches='tight', dpi=300)
    plt.show()
    

def pdf_to_images(pdf_path, output_folder, dpi=300, zoom_x=2.0, zoom_y=2.0):
    try:
        # 打开PDF文件
        pdf_document = fitz.open(pdf_path)
        
        for page_num in range(len(pdf_document)):
            # 获取页面
            page = pdf_document.load_page(page_num)
            # 设置缩放比例和旋转角度
            mat = fitz.Matrix(zoom_x, zoom_y)

            # 将页面转换为像素图
            pix = page.get_pixmap(matrix=mat, alpha=False, dpi=dpi)
            
            # 创建图像对象
            img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
            
            # 保存图像
            output_path = f"{output_folder}" #/page_{page_num + 1}.png
            img.save(output_path, quality=95)
            print(f"Saved {output_path}")
            return output_path
    except Exception as e:
        print(f"Error during PDF to image conversion: {e}")
        return None
    finally:
        pdf_document.close()


